<?php
class XA_Log {



	public static function log($params = array(), $log_list = 'app.log') {

		global $user;

		if (is_string($log_list)) {
			$log_list = array($log_list);
		}

		$line = array(
			  date('Y-m-d H:i:s')
			, $_SERVER['REMOTE_ADDR']
		);

		if (!empty($params['s']) && ($sid = session_id())) {
			$line[] = 's:'.$sid;
			unset($params['s']);
		}

		if (!empty($params['u']) && $user->id) {
			$line[] = 'u:'.$user->id;
			unset($params['u']);
		}

		foreach ($params as $key => $val) {
			$line[] = $key.':'.$val;
		}

		foreach ($log_list as $log) {
			if (!file_exists($dir = dirname(LOG_PATH.$log))) {
				mkdir($dir, 0777, true);
			}

			$file = fopen(LOG_PATH.$log, 'a');
			fwrite($file, implode(' ', $line)."\n");
			fclose($file);
		}
	}



	public static function getEntry($line) {
		$chunks = explode(' ', trim($line));

		$record = array(
			  'date' => array_shift($chunks).' '.array_shift($chunks)
			, 'ip' => array_shift($chunks)
		);

		foreach ($chunks as $item) {
			list($key, $val) = explode(':', $item);

			if ($key === 's') {
				$key = 'session_id';
			}

			if ($key === 'u') {
				$key = 'user_id';
			}

			$record[$key] = $val;
		}

		return $record;
	}
}
